﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace GanoESB.Business.Impl
{
    internal class Deployer : IDeployer
    {
        private ServiceBus serviceBus;

        public void StartScan(IServiceBus bus)
        {
            this.serviceBus = (ServiceBus)bus;

            string basePath = AppDomain.CurrentDomain.BaseDirectory;

            // 部署
            string[] dirs = Directory.GetDirectories(basePath);
            for (int i = 0; i < dirs.Length; i++)
            {
                string[] files = Directory.GetFiles(dirs[i], "service.config");
                for (int j = 0; j < files.Length; j++)
                {
                    serviceBus.RegisterComponent(GetComponentDescriptor(files[j]));
                }
            }
        }

        public void StopScan()
        {
        }

        private ComponentDescriptor GetComponentDescriptor(string fullpath)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(fullpath);
            XmlElement root = doc.DocumentElement;

            ComponentDescriptor cd = new ComponentDescriptor();
            cd.DeploymentFile = fullpath;

            XmlNode node = root.SelectSingleNode("component");

            cd.ComponentName = node.Attributes.GetNamedItem("name").Value;
            cd.ComponentClazz = GetString(node.Attributes.GetNamedItem("type"));
            cd.ServiceAssembly = GetString(node.SelectSingleNode("serviceAssembly"));

            List<ServiceDescriptor> descrList = new List<ServiceDescriptor>();
            XmlNodeList nodes = node.SelectNodes("service");
            foreach (XmlNode nd in nodes)
            {
                ServiceDescriptor descr = new ServiceDescriptor();
                descr.ServiceName = nd.Attributes.GetNamedItem("name").Value;
                descr.ServiceInterface = GetString(nd.SelectSingleNode("serviceInterface"));
                descr.ServiceClazz = GetString(nd.SelectSingleNode("serviceClazz"));
                descr.ComponentName = cd.ComponentName;
                descrList.Add(descr);
            }
            cd.ServiceDescriptors = descrList.ToArray();
            return cd;
        }

        private int GetInt32(XmlNode node)
        {
            if (node == null)
                return 0;

            string s = node is XmlAttribute ? node.Value : node.InnerText;

            if (string.IsNullOrEmpty(s))
                return 0;

            int n;
            if (int.TryParse(s, out n))
                return n;

            return 0;
        }

        private string GetString(XmlNode node)
        {
            if (node == null)
                return null;

            return node is XmlAttribute ? node.Value : node.InnerText;
        }
    }
}
